package com.spsoft.vatoutinv.service.matchflow.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spsoft.core.enums.ResponseEnum;
import com.spsoft.core.exception.BusinessException;
import com.spsoft.core.model.Result;
import com.spsoft.core.utils.ExcelUtils;
import com.spsoft.core.utils.SecurityUtils;
import com.spsoft.system.entity.NvatOutInvoiceDetails;
import com.spsoft.vatoutinv.constants.CommonConstant;
import com.spsoft.vatoutinv.constants.DictConstant;
import com.spsoft.vatoutinv.enums.CommonEnum;
import com.spsoft.vatoutinv.mapper.VatNvatOutInvoiceDetailsMapper;
import com.spsoft.vatoutinv.mapper.VatNvatOutInvoiceItemsMapper;
import com.spsoft.vatoutinv.model.dto.matchflow.VmsMatchFlowSelectPageDto;
import com.spsoft.vatoutinv.model.dto.matchflow.VmsSelectItemFlowPageDto;
import com.spsoft.vatoutinv.model.vo.matchflow.VmsMatchFlowApplyVo;
import com.spsoft.vatoutinv.model.vo.matchflow.VmsMatchFlowSelectItemVo;
import com.spsoft.vatoutinv.model.vo.matchflow.VmsMatchFlowSelectVo;
import com.spsoft.vatoutinv.model.vo.matchflow.excel.VmsMatchFlowSelectExcelVo;
import com.spsoft.vatoutinv.model.vo.vmstransactionflowinvoice.VmsTransactionFlowInvoicePageVo;
import com.spsoft.vatoutinv.service.matchflow.VmsMatchFlowSelectService;
import com.spsoft.vatoutinv.service.translate.impl.DictTranslate;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 手工匹配流水查询 服务实现类
 *
 * @author : chenxudong
 * @date : 2024/7/1 17:29
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class VmsMatchFlowSelectServiceImpl implements VmsMatchFlowSelectService {

    public static final String LOG_MSG = "(手工匹配流水查询实现层)";

    private final DictTranslate dictTranslate;

    private final VatNvatOutInvoiceDetailsMapper nvatOutInvoiceDetailsMapper;

    private final VatNvatOutInvoiceItemsMapper nvatOutInvoiceItemsMapper;

    @Override
    public Result<IPage<VmsMatchFlowSelectVo>> getPage(VmsMatchFlowSelectPageDto pageDto) {
        // 创建分页对象
        Page<VmsMatchFlowApplyVo> page = new Page<>(pageDto.getPageNo(), pageDto.getPageSize());
        // 交易机构下拉框处理
        String deptCode = pageDto.getDeptCode();
        if (StringUtils.isNotBlank(deptCode)) {
            List<String> deptCodeList = Arrays.asList(deptCode.split(","));
            pageDto.setDeptCodeList(deptCodeList);
        } else {
            pageDto.setDeptCodeList(Collections.singletonList(SecurityUtils.getDeptCode()));
        }
        // 开票日期处理 将yyyy-MM-dd转为yyyy-mm-dd hh24:mi:ss
        if (StringUtils.isNotBlank(pageDto.getKprqq()) && StringUtils.isNotBlank(pageDto.getKprqz())) {
            pageDto.setKprqq(DateUtil.format(DateUtil.beginOfDay(DateUtil.parseDate(pageDto.getKprqq())), CommonConstant.DATE_FORMAT_14));
            pageDto.setKprqz(DateUtil.format(DateUtil.endOfDay(DateUtil.parseDate(pageDto.getKprqz())), CommonConstant.DATE_FORMAT_14));
        }
        // 手工开票匹配流水情况查询
        IPage<VmsMatchFlowSelectVo> dataList = nvatOutInvoiceDetailsMapper.matchFlowSelect(page, pageDto);
        if (CollectionUtil.isNotEmpty(dataList.getRecords())) {
            for (VmsMatchFlowSelectVo vmsMatchFlowSelectVo : dataList.getRecords()) {
                // 查询发票明细信息
                List<VmsMatchFlowSelectItemVo> itemVoList = nvatOutInvoiceItemsMapper.matchFlowSelect(vmsMatchFlowSelectVo.getOidid());
                // 发票明细的匹配状态判断
                for (VmsMatchFlowSelectItemVo itemVo : itemVoList) {
                    if (ObjectUtil.isNotEmpty(itemVo.getNrmivid())) {
                        itemVo.setItemPpzt(CommonEnum.ITEM_PPZT_1.getValue());
                    } else {
                        itemVo.setItemPpzt(CommonEnum.ITEM_PPZT_0.getValue());
                    }
                }
                vmsMatchFlowSelectVo.setInvoiceItemList(itemVoList);
            }
        }
        return Result.OK(dataList);
    }

    @Override
    public void export(VmsMatchFlowSelectPageDto pageDto, HttpServletResponse response) {
        try {
            // 交易机构下拉框处理
            String deptCode = pageDto.getDeptCode();
            if (StringUtils.isNotBlank(deptCode)) {
                List<String> deptCodeList = Arrays.asList(deptCode.split(","));
                pageDto.setDeptCodeList(deptCodeList);
            } else {
                pageDto.setDeptCodeList(Collections.singletonList(SecurityUtils.getDeptCode()));
            }
            // 开票日期处理 将yyyy-MM-dd转为yyyy-mm-dd hh24:mi:ss
            if (StringUtils.isNotBlank(pageDto.getKprqq()) && StringUtils.isNotBlank(pageDto.getKprqz())) {
                pageDto.setKprqq(DateUtil.format(DateUtil.beginOfDay(DateUtil.parseDate(pageDto.getKprqq())), CommonConstant.DATE_FORMAT_14));
                pageDto.setKprqz(DateUtil.format(DateUtil.endOfDay(DateUtil.parseDate(pageDto.getKprqz())), CommonConstant.DATE_FORMAT_14));
            }
            // 手工开票匹配流水情况查询
            List<VmsMatchFlowSelectExcelVo> dataList = nvatOutInvoiceDetailsMapper.exportMatchFlowSelect(pageDto);
            if (CollectionUtil.isEmpty(dataList)) {
                throw new BusinessException(ResponseEnum.DATA_NOT_FIND_ERROR);
            }

            // 部分字段需要转换
            for (int i = 0; i < dataList.size(); i++) {
                VmsMatchFlowSelectExcelVo data = dataList.get(i);
                data.setXh(i + 1);
                // 发票种类处理
                if (StringUtils.isNotBlank(data.getFplx())) {
                    String fplx = dictTranslate.translate(DictConstant.VMS_FPLX, data.getFplx());
                    data.setFplx(StringUtils.isNotBlank(fplx) ? fplx : data.getFplx());
                }
                // 单位处理
                if (StringUtils.isNotBlank(data.getJldw())) {
                    String dw = dictTranslate.translate(DictConstant.VMS_JLDW, data.getJldw());
                    data.setJldw(StringUtils.isNotBlank(dw) ? dw : data.getJldw());
                }
                // 发票匹配状态
                if (CommonEnum.MATCHING_STATUS_0.getKey().equals(data.getPpzt())) {
                    data.setPpzt(CommonEnum.MATCHING_STATUS_0.getValue());
                } else {
                    data.setItemPpzt(CommonEnum.MATCHING_STATUS_1.getValue());
                }
                // 发票明细匹配状态
                if (ObjectUtil.isNotEmpty(data.getNrmivid())) {
                    data.setItemPpzt(CommonEnum.ITEM_PPZT_1.getValue());
                } else {
                    data.setItemPpzt(CommonEnum.ITEM_PPZT_0.getValue());
                }
                // 开票日期、匹配日期处理
                if (data.getKprq() != null) {
                    data.setKprqStr(DateUtil.format(data.getKprq(), CommonConstant.DATE_FORMAT_8));
                }
                if (data.getPprq() != null) {
                    data.setPprqStr(DateUtil.format(data.getPprq(), CommonConstant.DATE_FORMAT_8));
                }
            }

            // excel导出到指定模板中
            String rootPath = "export/matchFlowSelectTemplate.xlsx";
            InputStream fis = Thread.currentThread().getContextClassLoader().getResourceAsStream(rootPath);
            if (fis == null) {
                log.error("{}模板下载异常,读取不到文件", LOG_MSG);
                throw new BusinessException(ResponseEnum.BUSINESS_EXCEL_TEMPLATE_ERROR);
            }
            // 导出
            ExcelUtils.exportExcelWithTemplate(dataList, "手工开具发票匹配流水情况查询导出数据", response, fis);
        } catch (BusinessException e) {
            log.error("{}导出excel文件出现异常", LOG_MSG);
            throw new BusinessException(e.getCode(), e.getMsg());
        } catch (Exception e) {
            log.error("{}导出excel文件出现异常", LOG_MSG);
            throw new BusinessException(ResponseEnum.BUSINESS_ERROR.getCode(), e.getMessage());
        }
    }

    @Override
    public Result<IPage<VmsTransactionFlowInvoicePageVo>> queryFlowByItem(VmsSelectItemFlowPageDto pageDto) {
        // 判断该发票是否已匹配
        LambdaQueryWrapper<NvatOutInvoiceDetails> invoiceQuery = new LambdaQueryWrapper<>();
        invoiceQuery.select(NvatOutInvoiceDetails::getOidid, NvatOutInvoiceDetails::getPpzt);
        invoiceQuery.eq(NvatOutInvoiceDetails::getOidid, pageDto.getOidid());
        NvatOutInvoiceDetails nvatInvoice = nvatOutInvoiceDetailsMapper.selectOne(invoiceQuery);
        if (nvatInvoice == null || !CommonEnum.MATCHING_STATUS_1.getKey().equals(nvatInvoice.getPpzt())) {
            return Result.ERROR(ResponseEnum.INVOICE_ITEM_NOT_MATCH_ERROR);
        }

        // 创建分页对象
        Page<VmsTransactionFlowInvoicePageVo> page = new Page<>(pageDto.getPageNo(), pageDto.getPageSize());
        // 分页查询明细匹配的流水信息
        IPage<VmsTransactionFlowInvoicePageVo> dataList = nvatOutInvoiceItemsMapper.queryFlowByItem(page, pageDto);

        return Result.OK(dataList);
    }
}
